import { _decorator, Component, Input, input, instantiate, Node, Prefab, Vec3, RigidBody } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('AttackController')
export class AttackController extends Component {
    @property(Prefab)
    public bulletPrefab: Prefab = null;
    @property(Number)
    public bulletSpeed: number = 30;
    @property(Node)
    public bulletParent: Node = null;
    @property(Number)
    public fireRate: number = 0.2; // 每0.5秒发射一次子弹

    private isTouching: boolean = false;
    private fireTimer = 0;

    start() {
        input.on(Input.EventType.TOUCH_START, this.onTouchStart, this);
        input.on(Input.EventType.TOUCH_END, this.onTouchEnd, this)
    }
    onDestroy() {
        input.off(Input.EventType.TOUCH_START, this.onTouchStart, this);
        input.off(Input.EventType.TOUCH_END, this.onTouchEnd, this);
    }

    onTouchStart(){
        this.isTouching = true;
    }
    onTouchEnd() {
        this.isTouching = false;
        console.log("Touch Ended");
    }

    update(deltaTime: number) {
        if(this.isTouching){
            this.fireTimer += deltaTime;
            if(this.fireTimer > this.fireRate){
                this.fireTimer = 0;
                this.fire();
            }
        }
    }
    fire(){
        const bullet = instantiate(this.bulletPrefab);
        //bullet.setParent(this.node);
        bullet.setParent(this.bulletParent); //摄像机为父节点时，一动，子弹也要跟着动。
        //bullet.setPosition(0, 0, 0); //本地坐标，即相对于父节点摄像机的位置。
        bullet.setWorldPosition(this.node.position);//世界坐标。每次触摸时，子弹都会从摄像机位置发射出去。一次性的。
        const rgd = bullet.getComponent(RigidBody);
        if (rgd) {
            rgd.setLinearVelocity(new Vec3(0, 0, -this.bulletSpeed));
        }
    }
}


